package pro.shushi.pamirs.hr.core.action.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import pro.shushi.pamirs.boot.base.model.ServerAction;
import pro.shushi.pamirs.hr.api.model.auth.AppAuthResource;
import pro.shushi.pamirs.hr.core.manager.auth.AuthResourceManager;
import pro.shushi.pamirs.hr.core.manager.auth.MetaOperateManager;
import pro.shushi.pamirs.meta.annotation.Action;
import pro.shushi.pamirs.meta.annotation.Function;
import pro.shushi.pamirs.meta.annotation.Model;
import pro.shushi.pamirs.meta.annotation.fun.extern.Slf4j;
import pro.shushi.pamirs.meta.constant.ExpConstants;
import pro.shushi.pamirs.meta.constant.FunctionConstants;
import pro.shushi.pamirs.meta.enmu.ActionContextTypeEnum;
import pro.shushi.pamirs.meta.enmu.FunctionTypeEnum;
import pro.shushi.pamirs.meta.enmu.ViewTypeEnum;

import java.util.List;

@Slf4j
@Component
@Model.model(AppAuthResource.MODEL_MODEL)
public class AppAuthResourceAction {

    @Autowired
    private MetaOperateManager metaOperateManager;
    @Autowired
    private AuthResourceManager authResourceManager;

    @Transactional
    @Action.Advanced(name = FunctionConstants.create, managed = true, invisible = ExpConstants.idValueExist)
    @Action(displayName = "确定", summary = "创建", bindingType = ViewTypeEnum.FORM)
    @Function(name = FunctionConstants.create)
    @Function.fun(FunctionConstants.create)
    public AppAuthResource create(AppAuthResource data) {
        ServerAction action = metaOperateManager.buildServerAction(data);

        data.setResourceId(action.getId());
        data.construct();
        data.create();
        return data;
    }

    @Transactional
    @Action.Advanced(name = FunctionConstants.update, managed = true, invisible = "IS_BLANK(activeRecord.id)")
    @Action(displayName = "更新", summary = "修改", bindingType = ViewTypeEnum.FORM)
    @Function(name = FunctionConstants.update)
    @Function.fun(FunctionConstants.update)
    public AppAuthResource update(AppAuthResource data) {
        metaOperateManager.buildServerAction(data);
        data.updateById();
        return data;
    }

    @Function.Advanced(type = FunctionTypeEnum.DELETE)
    @Function.fun(FunctionConstants.deleteWithFieldBatch)
    @Function(name = FunctionConstants.delete)
    @Action(displayName = "删除", contextType = ActionContextTypeEnum.SINGLE_AND_BATCH)
    public List<AppAuthResource> delete(List<AppAuthResource> dataList) {
        dataList.forEach(data -> {
            data.deleteById();

            ServerAction serverAction = new ServerAction().setId(data.getResourceId()).queryById();
            serverAction.deleteById();
            metaOperateManager.actionMetaDelHandler(serverAction);
        });

        return dataList;
    }

}
